<template>
  <div>
    <!--搜索框-->
    <el-form :inline="true">
      <el-form-item>
        <el-input v-model="searchForm.username" placeholder="用户名" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button>搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="dialogFormVisible = true" v-if="hasAuth('sys:user:save')">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-popconfirm title="确定批量删除吗？" @confirm="delHandle(null)">
          <el-button type="danger" slot="reference" :disabled="delBtlStatus" v-if="hasAuth('sys:user:del')">批量删除</el-button>
        </el-popconfirm>
      </el-form-item>
    </el-form>

    <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          label="头像"
          width="120">
        <template slot-scope="scope">
          <el-avator size="small" :src="scope.row.avatar"></el-avator>
        </template>
      </el-table-column>
      <el-table-column
          prop="username"
          label="用户名"
          width="120"
          show-overflow-tooltip>
      </el-table-column>
      <el-table-column
          label="角色名称"
          width="180">
        <template slot-scope="scope">
          <el-tag style="margin-right: 5px;" size="small" type="info" v-for="item in scope.row.roles" :key="item.id">
            {{ item.name }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
          prop="email"
          label="邮箱">
      </el-table-column>
      <el-table-column
          prop="phone"
          label="手机号">
      </el-table-column>
      <el-table-column
          prop="status"
          label="状态"
          width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 0" size="small" type="danger">禁用</el-tag>
          <el-tag v-else-if="scope.row.status === 1" size="small" type="success">正常</el-tag>
        </template>
      </el-table-column>
      <el-table-column
          prop="created"
          label="创建时间">
      </el-table-column>
      <el-table-column
          label="操作"
          width="220">
        <template slot-scope="scope">
          <el-button type="text" @click="roleHandle(scope.row.id)">分配角色</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-button type="text" @click="repassHandle(scope.row.id, scope.row.username)">重置密码</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-button type="text" @click="editHandle(scope.row.id)">编辑</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-popconfirm title="确定要删除这条记录吗？">
            <el-button type="text" slot="reference">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!--页码-->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :total="total">
    </el-pagination>

    <!--  新增对话框  -->
    <el-dialog
        title="用户信息"
        :visible.sync="dialogFormVisible"
        width="600px">
      <el-form ref="editForm" :model="editForm" :rules="editFormRules" label-width="100px">
        <el-form-item label="用户名" prop="username" label-width="100px">
          <el-input v-model="editForm.username" autocomplete="off"></el-input>
          <el-alert
            title="初始密码为888888"
            :closable="false"
            type="info"
            style="line-height: 12px"></el-alert>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" label-width="100px">
          <el-input v-model="editForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone" label-width="100px">
          <el-input v-model="editForm.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status" label-width="100px">
          <el-radio-group v-model="editForm.status">
            <el-radio :label="0">禁用</el-radio>
            <el-radio :label="1">正常</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('editForm')">取消</el-button>
        <el-button type="primary" @click="submitEditForm('editForm')">确定</el-button>
      </div>
    </el-dialog>


    <!--  分配角色对话框  -->
    <el-dialog title="分配角色"
               :visible.sync="roleDialogFormVisible"
               width="600px"
               @close="resetForm('roleForm')">
      <el-form :model="roleForm" ref="roleForm">
        <el-tree
            :data="roleTreeData"
            show-checkbox
            ref="roleTree"
            :default-expand-all="true"
            :props="defaultProps">
        </el-tree>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="roleDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitRoleHandle('permForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "User",
  data() {
    return {
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      roleTreeData: [],
      editForm: {
        name: '',
        code: '',
        remark: '',
        status: ''
      },
      editFormRules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入唯一编码', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'blur' }
        ]
      },
      currentPage: 1,
      pageSize: 10,
      total: 2,
      searchForm: {
        username: ''
      },
      multipleSelection: [],
      roleDialogFormVisible: false,
      dialogFormVisible: false,
      delBtlStatus: true,
      tableData: [
        {
          name: '普通用户',
          code: 'normal',
          address: '上海市普陀区金沙江路 1518 弄',
          status: 1,
        },
        {
          name: '超级管理员',
          code: 'admin',
          address: '上海市普陀区金沙江路 1518 弄',
          status: 1
        }
      ],
      roleForm: {

      }
    }
  },
  created() {
    this.getUserList()
    this.$axios.get("/sys/role/list").then(res => {
      this.roleTreeData = res.data.data.records
    }).catch(err => {
      console.log(err)
    })
  },
  methods: {
    getUserList() {
      this.$axios.get("/sys/user/list", {
        params: {
          name: this.searchForm.username,
          currentPage: this.currentPage,
          size: this.size
        }
      }).then(res => {
        this.tableData = res.data.data.records
        this.size = res.data.data.size
        this.currentPage = res.data.data.currentPage
        this.total = res.data.data.total
      }).catch(err => {
        console.log(err)
      })
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleSelectionChange(val) {
      console.log(val)
      this.multipleSelection = val;
      this.delBtlStatus = val.length == 0;
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.size = val;
      this.getRoleList();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.getRoleList()
    },
    submitEditForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios.post('/sys/role/' + (this.editForm.id ? 'update' : 'save'), this.editForm).then(res => {
            console.log(res)
            this.$message({
              showClose: true,
              message: '恭喜你，操作成功',
              type: 'success',
              onClose: () => {
                this.getMenuTree();
              }
            });
            this.dialogVisible = false
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    editHandle(id) {
      this.$axios.get('/sys/role/info/' + id).then(res => {
        this.editForm = res.data.data
        this.dialogVisible = true
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.dialogVisible = false
      this.editForm = {}
    },
    handleClose() {
      this.resetForm('editForm')
    },
    delHandle(id) {
      let ids = []

      if (id) {
        ids.push(id)
      } else {
        this.multipleSelection.forEach(row => {
          ids.push(row.id)
        })
      }
      console.log(ids)
      this.$axios.post('/sys/role/delete/', ids).then(res => {
        console.log(res)
        this.$message({
          showClose: true,
          message: '恭喜你，操作成功',
          type: 'success',
          onClose: () => {
            this.getRoleList();
          }
        });
      })
    },
    permHandle(id) {
      console.log(id)
      this.permDialogVisible = true
      this.$axios.get("/sys/role/info/" + id).then(res => {
        this.$refs.permTree.setCheckedKeys(res.data.menuIds)
        this.permForm = res.data.data
      })
    },
    submitRoleHandle() {
      let roleIds = this.$refs.roleTree.getCheckedKeys()
      this.$axios.post("/sys/user/role/" + this.roleForm.id, roleIds).then(res => {
        console.log(res);
        this.$message({
          showClose: true,
          message: '恭喜你，操作成功',
          type: 'success',
          onClose: () => {
            this.getUserList()
          }
        })
        this.roleDialogVisible = false
      })
    },
    repassHandle(id, username) {
      this.$confirm('将重置用户【' + username + '】的密码，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.post('/sys/user/repass', id).then(() => {
          this.$message({
            showClose: true,
            message: '恭喜你，操作成功',
            type: 'success',
            onClose: () => {

            }
          })
        })
      })
    }
  }
}
</script>

<style scoped>

</style>
